<template>
  <div class="app-container">
    <!-- <el-button type="primary" @click="handleAddRole">新增</el-button> -->
    <el-table :data="rolesList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" label="奖品代号" width="220">
        <template slot-scope="scope">
          {{ scope.row.prizeCode }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="奖品名称" width="220">
        <template slot-scope="scope">
          {{ scope.row.prizeName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="概率（%）" width="220">
        <template slot-scope="scope">
          {{ scope.row.baseRate }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="份额">
        <template slot-scope="scope">
          {{ scope.row.maxNum }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="剩余份额">
        <template slot-scope="scope">
          {{ scope.row.num }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" title="编辑">
      <el-form :model="role" :rules="rules" ref="ruleForm" label-width="80px" label-position="left">
        <el-form-item label="奖品代号">
          <el-input disabled v-model="role.prizeCode" placeholder="请输入奖品代号" />
        </el-form-item>
        <el-form-item label="奖品名称" prop="prizeName">
          <el-input maxlength="30" v-model="role.prizeName" placeholder="请输入奖品名称" />
        </el-form-item>
        <el-form-item label="奖品概率" prop="baseRate">
          <el-input maxlength="6" v-model="role.baseRate" placeholder="请输入奖品概率" />
        </el-form-item>
        <el-form-item label="份额" prop="maxNum">
          <el-input maxlength="10" v-model="role.maxNum" placeholder="请输入份额" />
        </el-form-item>
        <el-form-item label="剩余份额">
          <el-input v-model="role.num" disabled placeholder="请输入剩余份额" />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确认</el-button>
      </div>
    </el-dialog>
    <pagination v-show="total > 0" layout="prev, pager, next" :total="total" :page.sync="listQuery.page"
      :limit.sync="listQuery.size" @pagination="getPrizeList" />
  </div>
</template>

<script>
import path from 'path'
import { deepClone } from '@/utils'
import { getPrizeList, deleteRole, updatePrize } from '@/api/role'
import Pagination from '@/components/Pagination'

export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (/^(100(\.00?)?|([1-9]\d?|\d)(\.\d{1,2})?)$/.test(value) && parseFloat(value) >= 0.01 && parseFloat(value) <= 100) {
          callback();
        } else {
          callback(new Error('概率范围为0.01-100.00'));
        }
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (/^(0|100000000|[1-9]\d{0,7})$/.test(value)) {
          callback();
        } else {
          callback(new Error('份额范围为0-100000000的整数'));
        }
      }
    };
    return {
      role: {},
      rules: {
        prizeName: [
          { required: true, message: '请输入奖品名称', trigger: 'blur' },
          { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
        ],
        baseRate: [
          { required: true, message: '请输入概率', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        maxNum: [
          { required: true, message: '请输入份额', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ],
      },
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      total: 0,
      listQuery: {
        page: 1,
        size: 10
      }
    }
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    this.getPrizeList()
  },
  methods: {
    async getPrizeList() {
      const res = await getPrizeList({ current: this.listQuery.page, size: this.listQuery.size })
      this.rolesList = res.data.records
      this.total = res.data.total
    },

    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        if (route.hidden) { continue }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title

        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleAddRole() {
      this.role = Object.assign({}, defaultRole)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.role = deepClone(scope.row)
      this.dialogType = 'edit'
      this.dialogVisible = true
    },
    handleDelete({ $index, row }) {
      this.$confirm('Confirm to remove the role?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      })
        .then(async () => {
          await deleteRole(row.key)
          this.rolesList.splice($index, 1)
          this.$message({
            type: 'success',
            message: 'Delete succed!'
          })
        })
        .catch(err => { console.error(err) })
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []

      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)

        // recursive child routes
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    async confirmRole() {
      const isEdit = this.dialogType === 'edit'
      if (isEdit) {
        console.log(this.role)
        const params = {
          id: this.role.id,
          baseRate: this.role.baseRate,
          maxNum: this.role.maxNum,
          prizeName: this.role.prizeName,
        }
        await updatePrize(params)
        this.dialogVisible = false
        this.$message.success('保存成功')
        this.getPrizeList()
      }
      
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    }
  },
  components: { Pagination },
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }

  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
